/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */

import { ModuleType } from '../enum/module-type-enum.js';
import { ModuleModel } from '../model/module/module-model.js';
import { ProjectModel } from '../model/project/project-model.js';
import { DependencyType } from '../project/dependency/core/dependency-interface.js';
import { DependencyManager } from '../project/dependency/dependency-manager.js';
import { TaskService } from '../tasks/service/task-service.js';

/**
 * 记录Project工程中的entry依赖的本地har的情况下，har的依赖链中只存在har 不存在hsp
 * 此时的har合并到entry的时候不需要生成resource_str目录
 */
class ModuleDependencyUtil {
  private pureHar: Set<string> = new Set();

  getPureHar(service: TaskService, module: ModuleModel, projectModel: ProjectModel, isFaMode: boolean): Set<string> {
    if (this.pureHar.size === 0) {
      this.init(service, module, projectModel, isFaMode);
    }
    return this.pureHar;
  }

  init(service: TaskService, module: ModuleModel, projectModel: ProjectModel, isFaMode: boolean) {
    if (!(module.getModuleType() === ModuleType.Entry)) {
      return;
    }
    const localDirectDependencies = service.getDirectDependencies().filter((dependency) => {
      return dependency.isLocal() && dependency.getDependencyType() === DependencyType.DEPENDENCY_TYPE_HAR;
    });

    // 判断entry依赖的har的依赖链是否存在本地hsp
    localDirectDependencies.forEach((dependency) => {
      const harModel = projectModel.getModuleModelByName(dependency.getModuleJsonObj()?.module?.name ?? dependency.getPackageName());
      if (harModel) {
        const dependencies = new DependencyManager(isFaMode, harModel, projectModel).collectAllDependencies().npmDependencies;
        const isImpure = dependencies.some((dependency) => dependency.isLocal() && dependency.getDependencyType() === DependencyType.DEPENDENCY_TYPE_HSP);
        if (!isImpure) {
          this.pureHar.add(harModel.getName());
          dependencies.forEach((dependency) => {
            this.pureHar.add(dependency.isLocal() ? dependency.getModuleJsonObj()?.module?.name ?? dependency.getPackageName() : dependency.getPackageName());
          });
        }
      }
    });
  }
}

export const moduleDependencyUtil = new ModuleDependencyUtil();
